<template>
  <div class="app-container">
    <el-form
      :model="searchParams"
      ref="searchForm"
      :inline="true"
      v-show="showSearch"
      label-position="left"
      label-width="100px"
    >
      <el-row>
        <el-col :span="6">
          <el-form-item label="爬虫编码" prop="spiderCode">
            <el-input
              v-model="searchParams.spiderCode"
              placeholder="请输入爬虫编码"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="爬虫名称" prop="spiderName">
            <el-input
              v-model="searchParams.spiderName"
              placeholder="请输入爬虫名称"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="网站根域名" prop="domain">
            <el-input
              v-model="searchParams.domain"
              placeholder="请输入网站根域名"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" @click="resetQuery"
              >重置</el-button
            >
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-circle-plus-outline"
          size="medium"
          @click="handleAdd"
          v-hasPermi="['crawlerModule:crawlerConfig:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="medium"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['crawlerModule:crawlerConfig:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="medium"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['crawlerModule:crawlerConfig:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="medium"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['crawlerModule:crawlerConfig:export']"
          >导出</el-button
        >
      </el-col>

      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="spiderConfigTableData"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="爬虫编码" align="center" prop="spiderCode" />
      <el-table-column label="爬虫名称" align="center" prop="spiderName" />
      <el-table-column label="网站根域名" align="center" prop="domain" />
      <el-table-column label="字符集" align="center" prop="charset" />

      <el-table-column label="睡眠时间(ms)" align="center" prop="sleepTime" />
      <el-table-column label="重试次数" align="center" prop="retryTimes" />
      <el-table-column label="线程数量" align="center" prop="threadCount" />
      <el-table-column label="使用代理" align="center" prop="useProxy">
        <template slot-scope="scope">
          <span v-if="scope.row.useProxy === 0">不使用</span>
          <span v-if="scope.row.useProxy === 1">使用代理</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="200"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="medium"
            type="text"
            icon="el-icon-edit-outline"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['crawlerModule:crawlerConfig:edit']"
            >编辑</el-button
          >
          <el-button
            size="medium"
            type="text"
            icon="el-icon-s-management"
            @click="goConfigField(scope.row)"
            v-hasPermi="['crawlerModule:crawlerConfig:detail']"
            >配置字段</el-button
          >
          <el-button
            size="medium"
            type="text"
            icon="el-icon-delete-solid"
            @click="handleDelete(scope.row)"
            v-hasPermi="['crawlerModule:crawlerConfig:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="searchParams.pageNum"
      :limit.sync="searchParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改爬虫模板对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="爬虫编码" prop="spiderCode">
              <el-input
                v-model="form.spiderCode"
                placeholder="请输入爬虫编码"
              />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="爬虫名称" prop="spiderName">
              <el-input
                v-model="form.spiderName"
                placeholder="请输入爬虫名称"
              />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="入口地址" prop="rntryUrls">
              <el-input v-model="form.rntryUrls" placeholder="请输入入口地址" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="目标URL正则" prop="targetRegex">
              <el-input
                v-model="form.targetRegex"
                placeholder="请输入目标URL正则"
              />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="级联发现URL" prop="cascade">
              <el-switch
                v-model="form.cascade"
                active-color="#13ce66"
                inactive-color="#ff4949"
                :active-value="1"
                :inactive-value="0"
              >
              </el-switch>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="网站根域名" prop="domain">
              <el-input v-model="form.domain" placeholder="请输入网站根域名" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="字符集" prop="charset">
              <el-input v-model="form.charset" placeholder="请输入字符集" />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="睡眠时间(ms)" prop="sleepTime">
              <el-input v-model="form.sleepTime" placeholder="请输入睡眠时间" />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="重试次数" prop="retryTimes">
              <el-input
                v-model="form.retryTimes"
                placeholder="请输入重试次数"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="线程数量" prop="threadCount">
              <el-input
                v-model="form.threadCount"
                placeholder="请输入线程数量"
              />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="使用代理" prop="useProxy">
              <el-switch
                v-model="form.useProxy"
                active-color="#13ce66"
                inactive-color="#ff4949"
                :active-value="1"
                :inactive-value="0"
              >
              </el-switch>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="打印日志" prop="showLog">
              <el-switch
                v-model="form.showLog"
                active-color="#13ce66"
                inactive-color="#ff4949"
                :active-value="1"
                :inactive-value="0"
              >
              </el-switch>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm"
          >确 定</el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  querySpiderConfig,
  delSpiderConfig,
  addSpiderConfig,
  updateSpiderConfig,
  exportSpiderConfig
} from '@/api/crawler/crawler'

export default {
  name: 'SpiderConfig',
  components: {},
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 模板资源表格数据
      spiderConfigTableData: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      searchParams: {
        pageNum: 1,
        pageSize: 10,
        domain: '',
        spiderCode: '',
        spiderName: ''
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        spiderCode: [
          { required: true, message: '请填写爬虫编码', trigger: 'blur' }
        ],
        spiderName: [
          { required: true, message: '请填写爬虫名称', trigger: 'blur' }
        ],
        domain: [
          { required: true, message: '请填写网站根域名', trigger: 'blur' }
        ],
        targetRegex: [
          { required: true, message: '请填写目标URL正则', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询模板资源列表 */
    getList() {
      this.loading = true
      querySpiderConfig(this.searchParams).then(response => {
        this.spiderConfigTableData = response.list
        this.total = response.total
        this.loading = false
      })
    },

    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },

    // 表单重置
    reset() {
      this.form = {
        spiderCode: undefined,
        spiderName: undefined,
        rntryUrls: undefined,
        targetRegex: undefined,
        cascade: undefined,
        domain: undefined,
        charset: undefined,
        sleepTime: undefined,
        retryTimes: undefined,
        threadCount: undefined,
        useProxy: undefined,
        showLog: undefined
      }
      this.resetForm('form')
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.searchParams.pageNum = 1
      this.getList()
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('searchForm')
      this.handleQuery()
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    /** 导出按钮操作 */
    handleExport() {
      const searchParams = this.searchParams
      this.$confirm('是否确认导出所有数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.exportLoading = true
          return exportSpiderConfig(searchParams)
        })
        .then(response => {
          this.download(response.msg)
          this.exportLoading = false
        })
        .catch(() => {})
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.form = {
        spiderCode: '',
        spiderName: '',
        rntryUrls: '',
        targetRegex: '',
        cascade: 0,
        domain: '',
        charset: 'utf8',
        sleepTime: '1000',
        retryTimes: 2,
        threadCount: 1,
        useProxy: 0,
        showLog: 1
      }
      this.title = '添加爬虫配置'
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()

      this.form = {
        id: row.id,
        spiderCode: row.spiderCode,
        spiderName: row.spiderName,
        rntryUrls: row.rntryUrls,
        targetRegex: row.targetRegex,
        cascade: row.cascade,
        domain: row.domain,
        charset: row.charset,
        sleepTime: row.sleepTime,
        retryTimes: row.retryTimes,
        threadCount: row.threadCount,
        useProxy: row.useProxy,
        showLog: row.showLog
      }
      this.open = true
      this.title = '修改爬虫配置'
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.buttonLoading = true
          if (this.form.id != null) {
            updateSpiderConfig(this.form)
              .then(response => {
                this.msgSuccess('修改成功')
                this.open = false
                this.getList()
              })
              .finally(() => {
                this.buttonLoading = false
              })
          } else {
            addSpiderConfig(this.form)
              .then(response => {
                this.msgSuccess('新增成功')
                this.open = false
                this.getList()
              })
              .finally(() => {
                this.buttonLoading = false
              })
          }
        }
      })
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids.join(',')

      this.$confirm(
        '是否确认删除爬虫模板编号为"' + ids + '"的数据项?',
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          this.loading = true
          return delSpiderConfig(ids)
        })
        .then(() => {
          this.loading = false
          this.getList()
          this.msgSuccess('删除成功')
        })
        .catch(() => {})
    },

    /** 进入配置字段页面 */
    goConfigField(row) {
      const rowId = row.id || this.ids[0]
      this.$router.push('/crawlerConfig/configField/' + rowId)
    }
  }
}
</script>
<style scoped lang="scss">
::v-deep .el-dialog__footer {
  text-align: center;
}
</style>